<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="ruleFormRef" status-icon>
          <h1>Hello</h1>
          <h2>欢迎使用</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" type="password" v-model="loginForm.password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button :loading="butLoading" type="primary" class="login_btn" @click="submit(ruleFormRef)">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="Login">
import { User, Lock } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';

import useUserStore from '@/store/modules/user';
import { useRouter, useRoute } from 'vue-router';
import { ElNotification, FormInstance, FormRules } from 'element-plus';
import { getTimeMessage } from '@/utils/time';
import type { LoginForm } from '@/api/user/type';
import { ResponseData } from '@/api/type';


let loginForm = reactive<LoginForm>({ username: 'admin', password: '111111' });

let userStore = useUserStore();

let router = useRouter();
let route = useRoute();

let butLoading = ref(false);

let ruleFormRef = ref<FormInstance>();

const submit = async (ruleForm: FormInstance | undefined) => {
  if (!ruleForm) return
  await ruleForm.validate((valid, fields) => {
    if (valid) {
      login();
    } else {
      console.log('error submit!', fields);
    }
  })
};

const login = async () => {
  butLoading.value = true;
  try {
    await userStore.userLogin(loginForm)

    butLoading.value = false;

    // 编程式导航
    const redirect = route.query.redirect
    router.push({ path: redirect as string || '/' });

    ElNotification({
      type: 'success',
      message: '登录成功',
      title: `Hi~ ${loginForm.username} ${getTimeMessage()}好！`,
    })
  } catch (error) {
    butLoading.value = false
    ElNotification({
      type: 'error',
      message: (error as ResponseData<string>).data,
    })
  }
};

const validatorUserName = (_rule: any, value: any, callback: any) => {
  if (value && /^[a-zA-Z0-9]{5,10}$/.test(value)) {
    callback()
  } else {
    callback(new Error('用户名为英文或数字长度在5到10之间'))
  }
}

const rules = ref<FormRules<LoginForm>>({
  username: [
    { required: true, message: '用户名不能空', trigger: 'blur' },
    { validator: validatorUserName, trigger: ['change', 'blur'] }
  ],
  password: [
    { required: true, message: '密码不能空', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度在6到10之间', trigger: ['change', 'blur'] },
  ],
});
</script>
<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
}

.login_form {
  position: relative;
  width: 80%;
  top: 30vh;
  background: url('@/assets/images/login_form.png') no-repeat;
  background-size: cover;
  padding: 40px;

  h1 {
    color: white;
    font-size: 40px;
  }

  h2 {
    font-size: 20px;
    color: white;
    margin: 20px 0px;
  }

  .login_btn {
    width: 100%;
  }
}
</style>
